#!/bin/sh

. /usr/share/common

MMC_MODULE="jzmmc_v12"

set_gpio() {
	echo_info "Set GPIO $1 to F$2 D$3"
	gpio-diag $1 func $2 drive $3
}

set_power() {
	# Set additional MMC GPIOs
	# This needs to run AFTER the driver has been loaded
	# for the SD card to mount during boot
	for gpio in $gpio_mmc_power; do
		[ "${#gpio}" -ne 3 ] && continue
		[ "${gpio%[oO]}" = "$gpio" ] && continue

		case "${gpio#??}" in
			"O")
				echo_info "Set GPIO "${gpio%[oO]}" high"
				gpio set "${gpio%[oO]}" 1
				;;
			"o")
				echo_info "Set GPIO "${gpio%[oO]}" low"
				gpio set "${gpio%[oO]}" 0
				;;
		esac
	done
}

load_module() {
	if grep -q "$MMC_MODULE" /proc/modules >/dev/null; then
		echo_error "$MMC_MODULE is already loaded"
		exit 1
	fi

	echo_info "Load $MMC_MODULE $MMC_PARAM"

	if ! modprobe $MMC_MODULE $MMC_PARAM; then
		echo_error "Failed to load module!"
		exit 1
	fi

	set_power
}

start() {
	echo_title "Initializing MMC"

	MMC_PARAM="cd_gpio_pin=${gpio_mmc_cd:-59}"
	load_module
}

case "$1" in
	start)
		start
		;;
	stop)
		true
		;;
	restart)
		stop
		sleep 1
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}" >&2
		exit 1
		;;
esac

exit 0
